package server

import (
	"errors"
	"github.com/google/uuid"
	"order/conmon/models/mysql"
	"order/conmon/models/redis"
	"order/conmon/proto/user"
	"order/pkg"
	"strconv"
)

func UserLogin(in *user.UserLoginReq) (*user.UserLoginResp, error) {
	u := mysql.User{}
	username, err := u.FindUserByUsername(in.Username)
	if err != nil {
		return nil, errors.New("查询失败")
	}
	if username.ID == 0 {
		return nil, errors.New("该用户不存在")
	}
	if username.Password != in.Password {
		return nil, errors.New("密码错误")
	}
	return &user.UserLoginResp{Greet: int64(username.ID)}, nil
}

func GoodsList(in *user.GoodsListReq) (*user.GoodsListResp, error) {
	g := mysql.Goods{}
	status, err := g.FindGoodsByStatus(in.GoodsStatus)
	if err != nil {
		return nil, errors.New("查询失败")
	}
	var list []*user.GoodsList
	for _, m := range status {
		list = append(list, &user.GoodsList{
			GoodsName:  m.GoodsName,
			GoodsPrice: float32(m.GoodsPrice),
			GoodsImg:   m.GoodsImg,
		})
		redis.SetGoods("Goods"+strconv.FormatInt(in.GoodsStatus, 10), m.GoodsName)
	}

	return &user.GoodsListResp{Item: list}, nil
}
func OrderGoods(in *user.OrderGoodsReq) (*user.OrderGoodsResp, error) {
	g := mysql.Goods{}
	id, err := g.FindUserById(in.GoodsId)
	if err != nil {
		return nil, errors.New("查询失败")
	}
	if id.ID == 0 {
		return nil, errors.New("没有该商品")
	}
	if id.GoodsNum < in.Num {
		return nil, errors.New("该商品库存不足")
	}
	o := mysql.Order{}
	orderSn := uuid.New().String()
	price := id.GoodsPrice * float64(in.Num)
	tx := mysql.DB
	tx.Begin()
	err = o.CreateOrder(in.UserId, in.GoodsId, orderSn, price)
	if err != nil {
		tx.Rollback()
		return nil, err
	}
	count := id.GoodsNum - in.Num
	err = g.UpdateGoodsNum(in.GoodsId, count)
	if err != nil {
		tx.Rollback()
		return nil, errors.New("修改失败")
	}
	tx.Commit()

	amount := strconv.FormatFloat(price, 'f', 1, 64)
	pay := pkg.Pay(id.GoodsName, orderSn, amount)
	return &user.OrderGoodsResp{Greet: pay}, nil
}
func OrderList(in *user.OrderListReq) (*user.OrderListResp, error) {
	o := mysql.Order{}
	list, err := o.OrderList()
	if err != nil {
		return nil, err
	}
	var List []*user.OrderList
	for _, m := range list {
		List = append(List, &user.OrderList{
			GoodsId: m.GoodsId,
			OrderSn: m.OrderSn,
			Price:   float32(m.Price),
			Status:  m.Status,
		})
	}
	return &user.OrderListResp{Item: List}, nil
}
